package org.mspring.mlog.service.bbs.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.mspring.mlog.entity.bbs.TopicReply;
import org.mspring.mlog.service.bbs.TopicReplyService;
import org.mspring.mlog.service.stat.TopicStatService;
import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.platform.dao.hibernate.GenericDao;
import org.mspring.platform.dao.hibernate.common.EnhancedRule;
import org.mspring.platform.dao.support.Sort;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author Gao Youbo
 * @since 2013年9月3日
 */
@Service
@Transactional
public class TopicReplyServiceImpl extends GenericDao<TopicReply, Long> implements TopicReplyService {

    @Autowired
    private TopicStatService topicStatService;

    @Override
    public TopicReply createReply(TopicReply reply) {
        // TODO Auto-generated method stub
        if (reply == null || reply.getTopic() == null) {
            return null;
        }
        if (reply.getAuthor() == null) {
            reply.setAuthor(SecurityUtils.getCurrentUser());
        }
        if (reply.getCreateTime() == null) {
            reply.setCreateTime(new Date());
        }
        return super.save(reply);
    }

    @Override
    public List<TopicReply> listReplyByTopic(Long topic, int pageNo, int pageSize, Sort sort) {
        // TODO Auto-generated method stub
        EnhancedRule rule = new EnhancedRule();
        rule.setPageSize(pageSize);
        rule.setPage(pageNo);
        rule.add(Restrictions.eq("topic.id", topic));

        if (sort != null) {
            if (sort.isAsc()) {
                rule.addOrder(Order.asc(sort.getField()));
            } else {
                rule.addOrder(Order.desc(sort.getField()));
            }
        }
        return list(rule);
    }

    @Override
    public int getReplyCount(Long topic) {
        // TODO Auto-generated method stub
        EnhancedRule rule = new EnhancedRule();
        rule.add(Restrictions.eq("topic.id", topic));
        return getHibernateTemplate().count(TopicReply.class, rule);
    }

    @Override
    public void deleteReply(Long... id) {
        // TODO Auto-generated method stub
        super.remove(id);
    }

    @Override
    public void deleteReplyByTopic(Long topic) {
        // TODO Auto-generated method stub
        executeUpdate("delete from TopicReply r where r.topic.id = ?", topic);
    }

}
